import { REGEXP_EMAIL, REGEXP_PHONE } from "@/utils";
import { authApi } from "@/api";
import { useCountDown } from "./use-count-down";

export const useSmsCode = () => {
  const loading = ref(false);
  const { counts, start, isCounting } = useCountDown(60);

  const initLabel = "获取验证码";
  const countingLabel = (second: number) => `${second}秒后重新获取`;
  const label = computed(() => {
    let text = initLabel;
    if (loading.value) {
      text = "";
    }
    if (isCounting.value) {
      text = countingLabel(counts.value);
    }
    return text;
  });

  /** 判断手机号码格式是否正确 */
  const isPhoneValid = (phone: string) => {
    if (phone.trim() === "") {
      window.$message?.error("手机号码不能为空！");
      return false;
    } else if (!REGEXP_PHONE.test(phone)) {
      window.$message?.error("手机号码格式错误！");
      return false;
    }
    return true;
  };

  /** 获取短信验证码 */
  const getSmsCode = async (phone: string) => {
    const valid = isPhoneValid(phone);
    if (!valid || loading.value) return;

    loading.value = true;
    const { status } = await authApi.codeByPhone(phone);
    if (status) {
      window.$message?.success("验证码发送成功！");
      start();
    }
    loading.value = false;
  };

  /** 判断邮箱格式是否正确 */
  const isEmailValid = (email: string) => {
    if (email.trim() === "") {
      window.$message?.error("邮箱不能为空！");
      return false;
    } else if (!REGEXP_EMAIL.test(email)) {
      window.$message?.error("邮箱格式错误！");
      return false;
    }
    return true;
  };

  /** 获取短信验证码 */
  const getEmailCode = async (email: string) => {
    const valid = isEmailValid(email);
    if (!valid || loading.value) return;

    loading.value = true;
    const { status } = await authApi.codeByEmail(email);
    if (status) {
      window.$message?.success("验证码发送成功！");
      start();
    }
    loading.value = false;
  };

  return {
    label,
    start,
    isCounting,
    getSmsCode,
    getEmailCode,
    loading,
  };
};
